<?php

class Application_Model_MotorcycleMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Motorcycle');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Motorcycle $motorcycle){
	
	
		$vehicleMapper = new Application_Model_VehicleMapper();
		$row = $vehicleMapper->save($motorcycle);
		//TODO set the object save function to return the id of the object saved
		//$where = array('model = ?' => (string)$product->getModel());
		$motorcycle->setVehicleId($row);
	
		$data = array(
				'id_vehicle' 	=> $motorcycle->getVehicleId(),
				'cylinder'			=> $motorcycle->getCylinder(),
		);
	
		if (null === ($id = $motorcycle->getMotorcycleId())) {
			unset($data['id_motorcycle']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_motorcycle = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Motorcycle $motorcycle)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$motorcycle->setMotorcycleId($row->id_motorcycle);
		$motorcycle->setVehicleId($row->id_vehicle);
		$motorcycle->setCylinder($row->cylinder);
	
		$vehicleMapper = new Application_Model_VehicleMapper();
		$motorcycle = $vehicleMapper->find($motorcycle->getVehicleId(), $motorcycle);
	
	
		return $motorcycle;
	}
	
	public function delete($id)
	{
	
		$motorcycle= new Application_Model_Motorcycle();
		$vehicleMapper = new Application_Model_VehicleMapper();
		$motorcycle = $this->find($id, new Application_Model_Motorcycle());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_motorcycle = ?' => $id));
		}
	
		$vehicleMapper->delete($motorcycle->getVehicleId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Motorcycle $motorcycle)
	{
		$vehicleMapper = new Application_Model_VehicleMapper();
		$requestBuilder = new Application_Model_Builder_Request();
		$doc->addField(Zend_Search_Lucene_Field::Text('cylinder', $requestBuilder->adjustnumber(5, $motorcycle->getCylinder(), '0'), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'motorcycle', 'utf-8'));
		$doc = $vehicleMapper->indexBuilder($doc, $motorcycle);
	
		return $doc;
	}
}